/*  header-comment
/*  file   : /Users/arida/react-hrm-h5/src/modules/steps/index
/*  author : arida
/*  date   : 2017-6-4 18:24:40
/*  last   : 2017-9-6 18:18:3
*/
import React, { Component } from "react";
import PropTypes from "prop-types";

import autobind from "autobind-decorator";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";

import { Button, Modal, List } from "@ali/ding-ui";

import { createForm } from "rc-form";

// components
import ProduceComponent from "../../components/produceComponent";
import Header from "./header";

// actions
import { fetchCompanyInfo } from "../../actions/finish";
import { startEntry } from "../../actions/welcome/";
import { saveUploadedFiles } from "../../actions/steps/getFiles.js";
import { fetchAllFields, saveAll } from "../../actions/steps/getUser";
import { showOrHideFooterBar } from "../../actions/footbar/index.js";

// utils
import { validator } from "../../utils/form.js";
import { getUrlParam } from "../../utils/common.js";
import getComponents from "./getComponents.js";
import { showMessage } from "../../utils/form.js";
import { get, set } from "../../utils/db.js";
import { getUrlHashParam } from "../../utils/urlParams.js";
import {
  setTitle,
  setRight,
  toast,
  close,
  confirm
} from "../../utils/dingtalk.js";
import { controlBack } from "../../utils/native.js";
import urlParams from "../../utils/urlParams";


// less
import "./steps.less";

const getCacheKey = () => `cache:${get("uid")}:V2.0:${get("corpId")}`;

// 开发测试企业 “小猴房产”的corpId
const devCorpId = "ding49d9a1090eee533a35c2f4657eb6378f";

// 如果是HR的话url中会有userId
function isHR() {
  return !!getUrlHashParam("userId");
}

// 特殊逻辑， 如果是四家特殊企业，直接提示并close
function isMediaCollector() {
  return (
    [
      "ding422801ddd5e6dc9035c2f4657eb6378f",
      "dingfbc28887e3bd673535c2f4657eb6378f",
      "dingeacb79c5b42de43e35c2f4657eb6378f",
      "ding86a9a9682604167035c2f4657eb6378f",
      "ding3f4e59195320857235c2f4657eb6378f"
    ].indexOf(getUrlParam("corpId")) !== -1
  );
}

function isForeign() {
  return (
    [
      "ding86a9a9682604167035c2f4657eb6378f",
      "ding3f4e59195320857235c2f4657eb6378f"
    ].indexOf(getUrlParam("corpId")) !== -1
  );
}

// 需求来源：
// 杭州网钉科技有限公司这家公司（corpId： ding10c505554116f7b735c2f4657eb6378f）不希望必须上传身份证才能提交入职登记表
function isRequired() {
  if (
    get("corpId") === "ding10c505554116f7b735c2f4657eb6378f" ||
    get("corpId") === devCorpId
  ) {
    return false;
  } else if (isHR()) {
    return false;
  }
  return true;
}

//将store注入组件的props
const mapStateToProps = state => ({
  source: state.STEPS_STEPTWO,
  finish: state.FINISH_COMPANY
});
//将action与dispatch进行绑定并注入组件的props
const mapDispatchToProps = dispatch => ({
  //区分绑定到props的action与传递的props
  actions: bindActionCreators(
    {
      dispatch,
      fetchCompanyInfo,
      saveAll,
      startEntry,
      fetchAllFields,
      saveUploadedFiles,
      showOrHideFooterBar
    },
    dispatch
  )
});

@connect(mapStateToProps, mapDispatchToProps)
class Entry extends Component {
  //constructor 非必需
  //默认props
  //获取dom节点的方法 ref={e =>{this.content = e}}>
  static defaultProps = {
    finish: {}
  };
  //propTypes 验证
  static propTypes = {
    form: PropTypes.shape({
      getFieldDecorator: PropTypes.func,
      getFieldsValue: PropTypes.func,
      getFieldProps: PropTypes.func,
      validateFields: PropTypes.func,
      setFieldsValue: PropTypes.func
    }),
    source: PropTypes.object,
    finish: PropTypes.object,
    actions: PropTypes.shape({
      dispatch: PropTypes.func.isRequired,
      saveAll: PropTypes.func,
      fetchCompanyInfo: PropTypes.func.isRequired,
      startEntry: PropTypes.func.isRequired,
      saveUploadedFiles: PropTypes.func.isRequired,
      fetchAllFields: PropTypes.func.isRequired,
      showOrHideFooterBar: PropTypes.func.isRequired
    }).isRequired
  };
  constructor(props) {
    super(props);
    this.state = {
      isEnjoin: false, //显示个人档案还是入职登记表 true : 入职登记表
      excuted: false, // 根据草稿，自动填充表单功能是否执行过
      isUpload: false, //是否上传
      isNew: false //是否新的
    };
  }

  componentDidMount() {
    let isEnjoin = false;
    let isNew = false;

    //首页过来的
    if(window.location.href.indexOf("hrcenter")!==-1){
      const { showOrHideFooterBar } = this.props.actions;
      showOrHideFooterBar && showOrHideFooterBar(false);
    }
    // this.needReload();
    this.props.actions.startEntry({ showLoading: false }).then(res => {
      if (res.success) {
        let title = "";
        if (isMediaCollector()) {
          title = isForeign() ? "Invitation" : "邀请函";
          if (res.result === -1) {
            dd.device.notification.alert({
              title: "",
              message: isForeign()
                ? "You've already completed the invitation letter"
                : "你已经填写过邀请函",
              buttonName: isForeign() ? "OK" : "我知道了",
              onSuccess: function() {
                close();
              }
            });
          }
        } else {
          if (res.result === -1) {
            title = "个人档案";
          } else {
            title = "入职登记表";
          }
        }

        isEnjoin = res.result !== -1;
        setTitle({
          title: title
        });

        setRight({
          show: true,
          onClick: () => {
            dd.device.notification.actionSheet({
              cancelButton: "取消",
              otherButtons: ["置顶到聊天页"],
              onSuccess: res => {
                if (res.buttonIndex === 0) {
                  dd.biz.util.stickPage({
                    url: window.location.href,
                    title: title
                  });
                }
              }
            });
          }
        });

        // controlBack(()=>{
        //   confirm({
        //     title: '草稿已自动保存',
        //     message: '你需要置顶到聊天，稍后填写吗？',
        //     buttonLabels: ['退出', '稍后填写'],
        //     cb: (res) => {
        //       if(res.buttonIndex === 0) {
        //         close()
        //       } else {
        //         dd.biz.util.stickPage({
        //           url: window.location.href,
        //           title: title
        //         })
        //       }
        //     }
        //   })
        // })

        let customLists = [];
        const userId = getUrlHashParam("userId");
        // HR获取某个人的信息
        this.props.actions.fetchAllFields(userId).then(res => {
          if (res.success && res.result.items) {
            customLists = res.result.items.map(custom => {
              return {
                title: custom.title,
                customFieldVOList: getComponents(custom.customFieldVOList).items
              };
            });
            //customList = getComponents(res.result.customFieldVOList).items;
            // re-render
            const { uid, employStatus } = res.result;
            if (employStatus === 1) {
              isNew = true;
            }
            this.setState({
              uid,
              customLists,
              isEnjoin,
              excuted: true,
              isNew
            });
          }
        });

        this.props.actions.fetchCompanyInfo();
      }
    });
  }

  componentWillUnmount() {

    //首页过来的
    if(window.location.href.indexOf("hrcenter")!==-1){
      const { showOrHideFooterBar } = this.props.actions;
      showOrHideFooterBar && showOrHideFooterBar(true);
    }
    window.needReload = null;
  }
  //重新加载
  needReload() {
    const t = this;
    window.needReload = function() {
      if (window.location.href.toLocaleLowerCase().indexOf("steps") !== -1) {
        //console.log("resume");
        //t.onRendered();
        const isUpload = get("isUploadCard") === "true";
        t.setState({
          isUpload
        });
      }
    };
  }

  @autobind
  onRendered() {
    // 2017-11-15： 新增功能，HR可以编辑员工信息
    // 如果是HR 不需要应用缓存
    if (!isHR()) {
      // 先set uid, 这样拿到的才是当前登陆人的id
      set("uid", this.state.uid);
      const cache = get(getCacheKey());
      if (cache) {
        this.props.form.setFieldsValue(cache);
      }
    }
  }

  @autobind
  saveUser() {
    const t = this;
    const isNew = t.state.isNew;
    const form = this.props.form.getFieldsValue();

    this.props.actions
      .saveAll({
        ...form,
        empUserId: getUrlParam("userId"), // HR更新某个人的信息
        部门: form.deptIds, // 后端直接根据“部门”关键字处理部门字段，需要值为Long型的部门ID
        手机号: undefined, // 手机号传给后端，后端会报错（通信录会更新失败）
        __photo__: undefined // 图片信息不回传， 有专门的接口
      })
      .then(res => {
        if (res.success) {

          if(isHR()){
            toast({
              text: isForeign() ? "success" : "提交成功",
              onSuccess() {
                history.go(-1);
              }
            });
          }else if (isMediaCollector()) {
            toast({
              text: isForeign() ? "success" : "提交成功",
              onSuccess() {
                close();
              }
            });
          } else {
            if (isNew) {
              //颜色
              const color = {
                dd_nav_bgcolor: "FF3296FA"
              };
              const url = urlParams.replaceSearch(color);
              window.location.href = url + "#/finish";
            } else {
              toast({
                icon: "success",
                text: "提交成功"
              });
            }

            // openLink("#/finish");
          }
          set(getCacheKey(), {}); // 清空草稿的唯一时机
        }
      });
  }

  @autobind
  isUploaded() {
    const user = this.props.source.user || {};

    return user.certUploaded;
  }

  @autobind
  submit() {
    // 是否实名认证通过
    const certed = this.isUploaded();

    if (isRequired() && !isHR()) {
      if (!certed) return toast({ text: "请上传身份证信息" });
    }

    this.props.form.validateFields(err => {
      if (!err) {
        // 媒体报名系统和HR不需要确认弹框
        if (isMediaCollector() || isHR()) {
          this.saveUser();
        } else {
          Modal.alert(
            "请确认以下信息",
            <span className="step-three-modal-text">
              <div className="title">
                <i />
                确认住址
              </div>
              1.我确认所填现住址为邮寄文件可送达地址
              <br />
              2.如现居住地变动，我会书面通知公司
              <br />
              3.因未及时通知公司造成文件邮寄无法送达，责任由我自负
              <br />
              <div className="title last">
                <i />
                确认内容真实性
              </div>
              1.我确认本表所填信息全部真实
              <br />
              2.如有虚假，同意按公司规章制度执行，包括与我解除劳动关系
              <br />
            </span>,
            [
              { text: "返回修改" },
              {
                text: "确认",
                onPress: () => {
                  this.saveUser();
                  // close the modal
                  //return false;
                }
              }
            ]
          );
        }
      } else {
        showMessage(err);
      }
    });
  }
  @autobind
  savePhoto(payload) {
    // HR可以编辑员工信息，因此保存图片需要增加userId参数
    this.props.actions.saveUploadedFiles({
      ...payload,
      userId: getUrlParam("userId")
    });
  }

  render() {
    const company = this.props.finish.company;
    const customLists = this.state.customLists || [];

    const isEnjoin = this.state.isEnjoin;
    if (company) {
      // avoid block scope by using var
      var {
        companyName = "",
        companyLogo,
        companyBackgroundImg
      } = this.props.finish.company;
    }
    const {
      getFieldDecorator,
      setFieldsValue,
      getFieldsValue
    } = this.props.form;

    const mediaText = isForeign() ? "Submit" : "提交";

    return (
      <div className="steps-con">
        <div className="scroll-body step-photo hrm-step3-upperform step-title">
          {!isHR() && (
            <Header
              logo={companyLogo}
              isEnjoin={isEnjoin}
              companyName={companyName}
              background={companyBackgroundImg}
              isNew={this.state.isNew}
            />
          )}

          {isHR() ? (
            ""
          ) : this.state.isNew ? (
            <div className="profile-title">请如实填写以下信息，以便HR为你办理入职手续</div>
          ) : (
            <div className="profile-title">请如实完善个人信息，方便HR办理相关手续</div>
          )}
          {customLists.map((custom, index) => {
            return (
              <List
                key={index}
                className="step-one-list hrm-step3-lowerform step-photo step-two-list step-one-list step-form"
              >
                <ProduceComponent
                  list={custom.customFieldVOList}
                  title={custom.title}
                  validator={validator} // form 校验
                  getFieldDecorator={getFieldDecorator}
                  onFileChange={this.onFileChange}
                  setFieldsValue={setFieldsValue}
                  getFieldsValue={getFieldsValue}
                  savePhoto={this.savePhoto} // 保存图片是单独的接口
                  onRendered={this.onRendered} // 子组件渲染之后 apply 草稿，否则不生效
                  certUploaded={this.isUploaded()} // 身份证是否上传
                  requireIDCard={isRequired()}
                />
              </List>
            );
          })}

          {this.state.excuted && (
            <div className="scroll-btn step-one-submit-btn stpes-btn">
              <Button onClick={() => this.submit()} across type="primary">
                {isMediaCollector() ? mediaText : isEnjoin ? "提交" : "更新个人档案"}
              </Button>
            </div>
          )}
        </div>
      </div>
    );
  }
}
export default createForm()(Entry);
